/*
 * =====================================================================================
 *
 *       Filename:  cs_common.cpp
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  2008年09月23日 13时58分05秒
 *       Revision:  none
 *       Compiler:  g++
 *
 *         Author:  ZhixiongHong (hzx), fishwarter@gmail.com
 *        Company:  Unioncast
 *
 * =====================================================================================
 */


#include "cs_common.h"

void pr_cpu_time(void)
{
	double user, sys;
	struct rusage myusage, childusage;

	if( getrusage( RUSAGE_SELF, &myusage) < 0)	
		cout << "geturage RUSAGE_SELF error " << endl;

	if( getrusage(RUSAGE_CHILDREN, &childusage) < 0)
		cout << "geturage RUSAGE_CHILDREN error" << endl;
	
	user = (double)myusage.ru_utime.tv_sec + myusage.ru_utime.tv_usec/1000000.0;
	user += (double)childusage.ru_utime.tv_sec + childusage.ru_utime.tv_usec/1000000.0;
	
	sys = (double)myusage.ru_stime.tv_sec + myusage.ru_stime.tv_usec/1000000.0;
	sys += (double)childusage.ru_stime.tv_sec + childusage.ru_stime.tv_usec/1000000.0;

	cout << "\nuser time " << user << "  sys time = " << sys << endl; 
}

void web_child(int sockfd)
{
	int 		nToWrite;
	ssize_t		nRead;
	char		line[MAXLINE], result[MAXN];

	init(result, MAXN);
	for(;;)
	{
		int ret = readable_timeo(sockfd, RECV_TIMEOUT);
		if( ret <= 0 )
		{
			//cout << "recv timeout " << endl;
			break;
		}
		//cout << "can read ....." << endl;
		nRead = recv(sockfd, line, MAXLINE, 0);
		if( nRead == 0 )
		{
			//cout << "nRead = 0 " << endl;
			break;
		}
		line[nRead] = '\0';
		nToWrite = atol(line);
		if( nToWrite <= 0 || nToWrite > MAXN)
		{
			cout << "client request for " << nToWrite << " bytes" << endl;
		}
		send(sockfd, result, nToWrite, 0);
	}
	//cout << "web_child end********" << endl;
}

void init(char* result, int len)
{
	for(int i = 0; i < len-1; i++)
	{
		result[i] = 'a';
	}
	result[len-1] = '\0';
}

int readable_timeo(int fd, int ms)
{
	fd_set	rset;

	FD_ZERO(&rset);
	FD_SET(fd, &rset);
	
	struct timeval 	tv;
	tv.tv_sec = ms/1000;
	tv.tv_usec = ms%1000;
	
	int ret = select(fd+1, &rset, NULL, NULL, &tv);
	return ret; /* >0 if descriptor is readable */
}
